import { useQueryClient } from '@tanstack/vue-query'

export function useOptimisticUpdate() {
  const queryClient = useQueryClient()

  const updatePostDetail = (postId, updateFn) => {
    // 获取查询客户端中的缓存数据
    queryClient.setQueryData(['postDetail', postId], (oldData) => {
      if (!oldData) return oldData

      return {
        ...oldData,
        result: updateFn(oldData.result)
      }
    })
  }

  const updatePostComment = (postId, commentId, updateFn) => {
    queryClient.setQueryData(['postComment', postId], (oldData) => {
      if (!oldData) return oldData

      return {
        ...oldData,
        result: {
          ...oldData.result,
          data: oldData.result.data.map((comment) => {
            if (comment.id === commentId) {
              return updateFn(comment)
            }
            return comment
          })
        }
      }
    })
  }

  return {
    updatePostDetail,
    updatePostComment
  }
} 